package generics;

import sun.security.pkcs11.wrapper.CK_ATTRIBUTE;

import java.util.*;
import java.lang.reflect.*;
import static net.mindview.util.Print.*;

public class ClassTypeCapture22<T> {
    Class<T> kind;

    public ClassTypeCapture22(Class<T> kind) {
        this.kind = kind;
    }

    public Object createNew(String typename)
            throws IllegalAccessException,
            InstantiationException,
            ClassNotFoundException {
        return Class.forName(typename).newInstance();

    }

    public Object createNew(String typename, Object... args)
            throws IllegalAccessException,
            InstantiationException,
            ClassNotFoundException,
            NoSuchMethodException,
            InvocationTargetException {
        switch (args.length) {
            case 1:
                return Class.forName(typename).getConstructor(args[0].getClass()).newInstance(args[0]);
            case 2:
                return Class.forName(typename).getConstructor(args[0].getClass(), args[1].getClass()).
                        newInstance(args[0], args[1]);
        }
        return null;
    }

    public static void main(String[] args) {
        ClassTypeCapture22<Building> ctcb = new ClassTypeCapture22<Building>(Building.class);
        ClassTypeCapture22<House> ctch = new ClassTypeCapture22<House>(House.class);
        try {
            Building b = (Building) ctcb.createNew("Building");
            System.out.println("House constructors:");
            Constructor[] ctors = House.class.getConstructors();
            for (Constructor ctor : ctors)
                System.out.println(ctor);
            House h = (House) ctch.createNew("House", "Hawaii");
            House h2 = (House) ctch.createNew("House", 3000);
            House h3 = (House) ctch.createNew("House", 5000);
            System.out.println("Constructed House objects:");
            System.out.println(h);
            System.out.println(h2);
            System.out.println(h3);

        }catch (IllegalAccessException e){
            System.out.println("IllegalAccessException in main");
        }catch(InstantiationException e){
            System.out.println("InstantiationException in main");
        }catch (ClassNotFoundException e){
            System.out.println("ClassNotFoundException in main");
        }catch (NoSuchMethodException e){
            System.out.println("NosuchMethodException in main");
        }catch (InvocationTargetException e){
            System.out.println("InvocationTargetException in main");
        }
    }
}
